﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KeshaParser
{
    class BaseParser
    {
        public event EventHandler<SimpleEventArgs> ParseError;

        protected Token currentToken;
        protected Scanner scanner;
        protected bool hasErrors = false;

        protected void Reset()
        {
            hasErrors = false;
            currentToken = null;
        }
        
        protected Token GetNextToken()
        {
            currentToken = scanner.GetNextToken();
            Check(currentToken.Type != TokenType.ERROR);
            return currentToken;
        }
        
        private void Check(bool success)
        {
            if (!success)
            {
                TriggerError();
            }
        }

        private void TriggerError()
        {
            EventHandler<SimpleEventArgs> handler = ParseError;

            if (handler != null && !hasErrors)
            {
                hasErrors = true;

                handler(this, new SimpleEventArgs(GetErrorText()));
            }
        }

        private string GetErrorText()
        {
            if (currentToken == null)
            {
                return "";
            }

            if (currentToken.Type == TokenType.ERROR)
            {
                return "at " + scanner.GetCurrentPositionAsString() + 
                        ": Unknown lexeme " + currentToken.Attribute;
            }

            return "Unexpected token at " +
                   scanner.GetCurrentPositionAsString() +
                   " " + currentToken.Attribute + "(" + currentToken.Type + ")";
        }
    }
}
